package com.example.administrator.hqq.activity.register;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertView;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.alertview.OnItemClickListener;
import com.example.administrator.hqq.activity.group.CreateGroupChatActivity;
import com.example.administrator.hqq.activity.mine.AmendUserDataActivity;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.MessageBean;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.bean.event.RegisterEvent;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.CameraUtils;
import com.example.administrator.hqq.utils.MyTextUtils;
import com.example.administrator.hqq.utils.SketchTextWatcher;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.example.administrator.hqq.utils.transform.GlideCircleTransform;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * @author 康海涛
 * @describe:昵称头像
 */

@RuntimePermissions
public class SetMessageActivity extends MyActivity {

    @BindView(R.id.user_name)
    EditText userName;
    @BindView(R.id.default_head_portrait)
    ImageView defaultHeadPortrait;
    @BindView(R.id.uploading_head_portrait)
    ImageView uploadingHeadPortrait;
    @BindView(R.id.skip_activity)
    TextView skipActivity;
    @BindView(R.id.skip_activity_auto)
    RelativeLayout skipActivityAuto;
    @BindView(R.id.app_return)
    ImageView appReturn;
    private String TAG = this.getClass().getSimpleName();
    private List<MessageBean.DataBean> data;
    private String picId;
    private String url="";
    private QNTokenBean qnTokenBean;
    private AlertView photoTypeAlertView;

    public static void start(Activity context, String phone, String code, String sex, String birthday) {
        Intent intent = new Intent(context, SetMessageActivity.class);
        Log.e("kang", "start: " + phone);
        intent.putExtra(LoongsConfig.phone, phone);
        intent.putExtra(LoongsConfig.code, code);
        intent.putExtra(LoongsConfig.sex, sex);
        intent.putExtra(LoongsConfig.birth, birthday);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_message);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initview();
    }

    private void initview() {
        data = new ArrayList<>();
        SketchTextWatcher sketchTextWatcher = new SketchTextWatcher(userName, 30);
        userName.addTextChangedListener(sketchTextWatcher);
    }

    @OnClick({R.id.app_return, R.id.default_head_portrait, R.id.uploading_head_portrait, R.id.skip_activity_auto})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.app_return:
                finish();
                break;
            case R.id.default_head_portrait:
                //跳转到默认头像选择页面
                Intent intent = new Intent(this, HeadPortraitActivity.class);
                startActivityForResult(intent,20);
                break;
            case R.id.uploading_head_portrait:
                //选择拍摄或者相册
                photoTypeAlertView = AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == -1) {
                            photoTypeAlertView.dismiss();
                        } else if (position == 0) {
                            SetMessageActivityPermissionsDispatcher.startLocationWithCheck(SetMessageActivity.this);
                        } else if (position == 1) {
                            SetMessageActivityPermissionsDispatcher.startStorageWithCheck(SetMessageActivity.this);
                        }
                    }
                });
                photoTypeAlertView.show();
                break;
            case R.id.skip_activity_auto:
                nextPage();
                break;
        }
    }

    /**
     * 跳转下一页
     */
    private void nextPage() {
        String s = userName.getText().toString();
        Log.e(TAG, "nextPage: "+url );
        if (!TextUtils.isEmpty(s)) {
            if (MyTextUtils.isEmptyString(userName))
            {
                ToastUtils.showShort("昵称不能全是空格");
                return;
            }
            if (!TextUtils.isEmpty(url)) {
                Intent intent = new Intent(this, HobbiesActivity.class);
                Log.e("kang", "Message给兴趣: " + getIntent().getStringArrayExtra(LoongsConfig.phone));
                intent.putExtra(LoongsConfig.phone, getIntent().getStringExtra(LoongsConfig.phone));
                intent.putExtra(LoongsConfig.code, getIntent().getStringExtra(LoongsConfig.code));
                intent.putExtra(LoongsConfig.sex, getIntent().getStringExtra(LoongsConfig.sex));
                intent.putExtra(LoongsConfig.birth, getIntent().getStringExtra(LoongsConfig.birth));
                intent.putExtra(LoongsConfig.user_name, s);
                intent.putExtra(LoongsConfig.url, url);
                startActivity(intent);
            } else {

                Toast.makeText(this, "请选择头像", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "请设置用户名", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("申请相机权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startLocation() {
        CameraUtils.getInstance().takeCamera(this);
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRetionaleForStorage(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.storage_permission))
                .setPositiveButton(getString(R.string.agree), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(getString(R.string.refuse), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showNeverAskForStorage() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showDeniedForStorage() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void startStorage() {
        CameraUtils.getInstance().openAlbum(this);
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SetMessageActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==20&&resultCode==111)
        {
            url=data.getStringExtra(LoongsConfig.picName);
            String pic_url = data.getStringExtra(LoongsConfig.pic_Url);
            defaultHeadPortrait.setImageResource(getResourceID(pic_url));
            uploadingHeadPortrait.setImageDrawable(getDrawable(R.drawable.uploading_head_portrait));
            Log.e(TAG, "onActivityResult: "+url );
        }
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()){
                    CameraUtils.getInstance().cropPicture(SetMessageActivity.this, path,1,1);//裁剪图片
                }
            }

            @Override
            public void selectPictureFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()){
                    CameraUtils.getInstance().cropPicture(SetMessageActivity.this, path,1,1);//裁剪图片
                }
            }
            @Override
            public void cropPictureFinish(String path) {
                getQNToken(path);
            }
        });
    }
    public void getQNToken(String path) {
        final File picFile = new File(path);
        OkHttpUtils.get().url(UrlFactory.getQNToken())
                .addParams(LoongsConfig.id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.type, LoongsConfig.USER)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e,int id) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String s,int id) {
                Log.e(TAG, "onResponse: " + s);
                Gson gson = new Gson();
                qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                if (qnTokenBean.getCode() == 200)
                    UploadManagerUtils.getUploadManager().put(picFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Log.i("qiniu", "Upload Success");
//                                Glide.with(SetMessageActivity.this)
//                                        .load(qnTokenBean.getUrl())
//                                        .bitmapTransform(new CenterCrop(SetMessageActivity.this), new GlideCircleTransform(SetMessageActivity.this))
//                                        .into(groudPic);
                                url=qnTokenBean.getId();
                                defaultHeadPortrait.setImageDrawable(getDrawable(R.drawable.default_head_portrait));
                                Glide.with(SetMessageActivity.this)
                                        .load(qnTokenBean.getUrl())
                                        .bitmapTransform(new GlideCircleTransform(SetMessageActivity.this))
                                        .into(uploadingHeadPortrait);
                            } else {
                                Log.i("qiniu", "Upload Fail");
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            }
                            Log.i("qiniu", key + ", " + info + ", " + res);
                        }
                    }, null);
            }
        });
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(RegisterEvent registerEvent){
        switch (registerEvent.getType()) {
            case BACK:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public int  getResourceID(String imageName){
        Context ctx=getBaseContext();
        int resId = getResources().getIdentifier(imageName, "drawable", ctx.getPackageName());
        //如果没有在"mipmap"下找到imageName,将会返回0
        return resId;
    }
}
